package com.jy.framework.filter;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.jy.framework.sys.entity.SysUserEntity;
import com.jy.framework.sys.shiro.ShiroUtils;
import com.jy.framework.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

/**
 * @Author JuiceYan
 * disception 自动填充公共字段
 * @date 2018-12-15 15:50:52
 */
@Slf4j
public class CommonFieldMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            SysUserEntity user = getCurrentUser();
            if (user != null) {
                this.setFieldValByName("createTime", DateUtils.formatData(), metaObject);
                this.setFieldValByName("delFlag", 0, metaObject);
                this.setFieldValByName("createBy", user.getId(), metaObject);
                this.setFieldValByName("updateTime", DateUtils.formatData(), metaObject);
                this.setFieldValByName("updateBy", user.getId(), metaObject);
                if (metaObject.hasGetter("deptId")&&metaObject.getValue("deptId") == null){
                    this.setFieldValByName("deptId", user.getDeptId(), metaObject);
                }
                if (metaObject.hasGetter("deptName")&&metaObject.getValue("deptName") == null){
                    this.setFieldValByName("deptName", user.getDeptName(), metaObject);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {

        try {
            SysUserEntity user = getCurrentUser();
            if (user != null) {
                this.setFieldValByName("updateTime", DateUtils.formatData(), metaObject);
                this.setFieldValByName("updateBy", user.getId(), metaObject);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
    }

    private SysUserEntity getCurrentUser() {
        SysUserEntity user = ShiroUtils.getUserEntity();
        return user;
    }
}